package doc.ic.walkmore.DAO;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Pair;
import doc.ic.walkmore.DAO.model.Steps;

public class StepsDataSource {

	  // Database fields
	  protected SQLiteDatabase database;
	  private MySQLiteHelper dbHelper;
	  protected String[] allColumns = { MySQLiteHelper.COLUMN_ID,
	      MySQLiteHelper.COLUMN_NUMBER,
	      MySQLiteHelper.COLUMN_TIME,
	      MySQLiteHelper.COLUMN_ACTIVITY,
	      MySQLiteHelper.COLUMN_DISTANCE,
	      MySQLiteHelper.COLUMN_DATE};
	  
	  SimpleDateFormat dayFormating = new SimpleDateFormat("yyyy-MM-dd");

	  public StepsDataSource(Context context) {
	    dbHelper = new MySQLiteHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	  }

	  public void close() {
	    dbHelper.close();
	  }
	  
	  public boolean hasData(String date) {
		  HashMap<String, Pair<Long, Long>> total = getTotalStepsBy(date);
		  return !total.isEmpty();
	  }
	  
	  public List<Steps> getAllSteps() {
	    List<Steps> stepss = new ArrayList<Steps>();

	    Cursor cursor = database.query(MySQLiteHelper.TABLE_STEPS,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Steps steps = cursorToSteps(cursor);
	      stepss.add(steps);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return stepss;
	  }

	  public void flushTable() {
		  database.delete(MySQLiteHelper.TABLE_STEPS, null, null);
	  }
	  
	  public List<Steps> getStepsBy(ContentValues values) {
		List<Steps> stepss = new ArrayList<Steps>();
		  
		String selection = "";
		ArrayList<String> selectionArgs = new ArrayList<String>();
		boolean first = true;
		for (Entry<String, Object> select : values.valueSet()) {
			String key = select.getKey(); String value =(String)select.getValue();
			if (!first)
				selection += " AND ";
			if (key.compareTo(MySQLiteHelper.COLUMN_DATE) == 0)
				selection += ("date("+MySQLiteHelper.COLUMN_DATE+") = date('?')");
			else
				selection += (key +" = ?");
			selectionArgs.add(value);
			first = false;
		}
		
		Cursor cursor = database.query(MySQLiteHelper.TABLE_STEPS,
		        allColumns, selection, (String[]) selectionArgs.toArray(), null, null, MySQLiteHelper.COLUMN_NUMBER);
		
	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Steps steps = cursorToSteps(cursor);
	      stepss.add(steps);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
		  
		return stepss;
	  }
	  
	  /**
	   * Data to send to view
	   * @param date
	   * @return
	   */
	  public HashMap<String, Pair<Long, Long>> getTotalStepsBy(String date) {
		HashMap<String, Pair<Long, Long>> result = new HashMap<String, Pair<Long,Long>>();
		
		String[] colums = {MySQLiteHelper.COLUMN_ACTIVITY,
				"sum("+MySQLiteHelper.COLUMN_NUMBER+")",
				"sum("+MySQLiteHelper.COLUMN_DISTANCE+")"
		};
		
		Cursor cursor = database.query(MySQLiteHelper.TABLE_STEPS,
		        colums, "date("+MySQLiteHelper.COLUMN_DATE+") = date('"+date+"')", null, MySQLiteHelper.COLUMN_ACTIVITY, null, null);
		
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Pair<Long, Long> p = new Pair<Long, Long>(cursor.getLong(1), cursor.getLong(2));
			result.put(cursor.getString(0), p);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		  
		return result;
	  }
	  
	  /**
	   * Data to send to daily graph
	   * @param date
	   * @return
	   */
	  public HashMap<String, Long> getTotalStepsByHour(String date) {
		HashMap<String, Long> result = new HashMap<String, Long>();
		
		String[] colums = {"strftime('%H', "+MySQLiteHelper.COLUMN_DATE+") as hour",
				"sum("+MySQLiteHelper.COLUMN_NUMBER+")"
		};
		
		Cursor cursor = database.query(MySQLiteHelper.TABLE_STEPS,
		        colums, "date("+MySQLiteHelper.COLUMN_DATE+") = date('"+date+"')", null, "hour", null, null);
		
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			result.put(cursor.getString(0), cursor.getLong(1));
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		  
		return result;
	  }
	  
	  protected Steps cursorToSteps(Cursor cursor) {
	    Steps steps = new Steps();
	    steps.setId(cursor.getLong(0));
	    steps.setNumber(cursor.getLong(1));
	    steps.setTime(cursor.getLong(2));
	    steps.setActivity(cursor.getString(3));
	    steps.setDistance(cursor.getLong(4));
	    steps.setDate(cursor.getString(5));
	    return steps;
	  }
} 